import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:easydubbing/utils/FutureDioToken.dart';
import 'package:easydubbing/utils/SpUtil.dart';
import 'package:easydubbing/utils/api.dart';
import 'package:easydubbing/utils/style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loading_indicator_view/loading_indicator_view.dart';

import 'login.dart';

class UserInfo extends StatefulWidget{
  UserInfoState createState() =>UserInfoState();
}
class UserInfoState extends State<UserInfo> {
  String avatar;
  int uid;
  String alias;
  String desc;
  TextEditingController aliasEditingController;
  TextEditingController descEditingController;
  File image;
  bool hasChosen = false;

  selectPic() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      this.image = image;
      if(this.image!=null){
        hasChosen = true;
      }else{
        hasChosen = false;
      }
    });
  }

  @override
  void initState() {
    if(SpUtil.sharedPreferences.getString('avatar')==""||SpUtil.sharedPreferences.getString('avatar')==null) {
      avatar ='https://img-blog.csdnimg.cn/20210610163006523.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3loMDAxNg==,size_16,color_FFFFFF,t_70#pic_center';
    }else{
      avatar = SpUtil.sharedPreferences.getString('avatar');
    }
    uid = SpUtil.sharedPreferences.getInt('uid');
    alias = SpUtil.sharedPreferences.getString('alias');
    desc = SpUtil.sharedPreferences.getString('desc');
    aliasEditingController = new TextEditingController();
    descEditingController = new TextEditingController();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print(SpUtil.sharedPreferences.getString('avatar'));
    return Theme(
        data: ThemeData(
          appBarTheme: AppBarTheme.of(context).copyWith(
            // 方式1
            color: Colors.yellow,
          ),
        ),
        child:  Scaffold(
            appBar:AppBar(
              centerTitle: true,
              automaticallyImplyLeading: true,
              title: Text('修改个人信息',style: TextStyle(color: ProjectColor.mainColor),),
              elevation: 0.5,
              brightness: Brightness.light,
              backgroundColor: Colors.white,
              leading: Container(
                margin: EdgeInsets.all(10),
                color: Colors.white,
                child: IconButton(
                    icon: Icon(
                      Icons.arrow_back_ios,
                      size: 20,
                      color: ProjectColor.mainColor,
                    ),
                    onPressed: () {
                      Navigator.pop(context); // 关闭当前页面
                    },
                ),
              ),
            ),
            body: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  alignment: Alignment.center,
                  child:InkWell(
                    splashColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                    onTap: ()=>selectPic(),
                    child: Container(
                      height: 80,
                      width:80,
                      margin: EdgeInsets.only(top: 20),
                      child: ClipOval(
                        child: hasChosen?Image.file(image):CachedNetworkImage(
                          imageUrl: avatar,
                        ),
                      ),
                    ),
                  )
                ),
                Container(
                    margin: EdgeInsets.only(top:20,bottom: 5,left: 50),
                    child: Row(
                      children: [
                        Container(
                          child: Text('昵称：'),
                        ),
                        Container(
                          width: 200,
                          height: 25,
                          margin: EdgeInsets.only(left: 10),
                          child:TextField(
                            cursorColor: Color(0xFFBBBBBB),
                            cursorWidth: 1,
                            controller: aliasEditingController,
                            maxLines: 1,
                            decoration: InputDecoration(
                              hintText: alias,
                              hintStyle: TextStyle(color: Color(0xFFbbbbbb),),
                            ),
//                    obscureText: !isShowPwd,
                          ),
                        )
                      ],
                    )
                ),
                Container(
                    margin: EdgeInsets.only(top:20,bottom: 5,left: 50),
                    child: Row(
                      children: [
                        Container(
                          child: Text('描述：'),
                        ),
                        Container(
                          width: 200,
                          height: 25,
                          margin: EdgeInsets.only(left: 10),
                          child:TextField(
                            cursorColor: Color(0xFFBBBBBB),
                            cursorWidth: 1,
                            controller: descEditingController,
                            maxLines: 1,
                            decoration: InputDecoration(
                              hintText: desc,
                              hintStyle: TextStyle(color: Color(0xFFbbbbbb),),
                            ),
                          ),
                        )
                      ],
                    )
                ),
                Spacer(),
                InkWell(
                  onTap: () async {
                    if(aliasEditingController.value.text.length>15){
                      showDialog(
                          context: context,
                          builder: (context){
                            return AlertDialog(
                              shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                              title: Text('提示'),
                              content: SingleChildScrollView(
                                child: ListBody(
                                  children: <Widget>[
                                    Text('昵称长度已超过15，请重新输入'),
                                  ],
                                ),
                              ),
                              actions: <Widget>[
                                TextButton(
                                  child: Text('确定',style: TextStyle(color: Color(0xFFF16050)),),
                                  onPressed: () {
                                    Navigator.pop(context);
                                  },
                                ),
                              ],
                            );
                          }
                      );
                    }else{
                      BuildContext buildContext = context;
                      showDialog(
                          context: buildContext,
                          barrierDismissible: false,
                          builder: (buildContext){
                            return AlertDialog(
                                shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                title: Text('提示'),
                                content: Container(
                                  height: 100,
                                  child: Column(
                                    children: [
                                      Container(
                                        width: 50,
                                        height: 50,
                                        child: Center(
                                          child: Container(
                                            width: 50,
                                            height: 50,
                                            child: LineSpinFadeLoaderIndicator(
                                              ballColor: ProjectColor.mainColor,
                                            ),
                                          ),
                                        ),
                                      ),
                                      SizedBox(height: 10,),
                                      Text("修改中，请耐心等待~")
                                    ],
                                  ),
                                )
                            );
                          }
                      );
                      if(image!=null){
                        var image = await MultipartFile.fromFile(
                          this.image.path,
                          filename: "avatar",
                        );
                        FormData formData = FormData.fromMap({"avatar":image});
                        FutureDio("upload", Api.userAvatar,{
                          "uid":uid,
                        },formData: formData).then((value) {
                          setState(() {
                            hasChosen = false;
                            this.image = null;
                            SpUtil.sharedPreferences.setString('avatar', value.data["data"]);
                          });
                          Navigator.pop(buildContext);
                          Navigator.pop(context);
                          Fluttertoast.showToast(
                              msg: '修改成功',
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              backgroundColor: Colors.black38,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                        });
                      }
                      FutureDio('post', Api.userInfo, {
                        "uid":uid,
                        "alias":aliasEditingController.value.text==""?alias:aliasEditingController.value.text,
                        "desc":descEditingController.value.text==""?desc:descEditingController.value.text,
                      }).then((value) {
                        if(value.data["msg"]!='ok'){
                          Fluttertoast.showToast(
                            msg: '更新失败',
                            fontSize: 14,
                            gravity: ToastGravity.BOTTOM,
                            textColor: Colors.black,
                          );
                        }else {
                          if(aliasEditingController.value.text!=""){
                            SpUtil.sharedPreferences.setString('alias', aliasEditingController.value.text);
                          }
                          if(descEditingController.value.text!=""){
                            SpUtil.sharedPreferences.setString('desc', descEditingController.value.text);
                          }
                        }
                        if(image==null){
                          Navigator.pop(buildContext);
                          Navigator.pop(context);
                        }
                      });
                    }
                  },
                  child:
                  Container(
                      alignment: Alignment.center,
                      child: Container(
                        width:200,
                        height: 40,
                        margin: EdgeInsets.only(bottom: 15),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: ProjectColor.deepColor,
                          borderRadius: BorderRadius.all(Radius.circular(15)),
                        ),
                        child: Text('提交',style: TextStyle(color: Colors.white,fontSize: 16),),
                      )
                  ),
                ),
                InkWell(
                  onTap: (){
                    showDialog(
                        context: context,
                        builder: (context){
                          return AlertDialog(
                            shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                            title: Text('提示'),
                            content: SingleChildScrollView(
                              child: ListBody(
                                children: <Widget>[
                                  Text('确定退出吗？'),
                                ],
                              ),
                            ),
                            actions: <Widget>[
                              TextButton(
                                child: Text('取消',style: TextStyle(color: ProjectColor.secColor),),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                              TextButton(
                                child: Text('确定',style: TextStyle(color: ProjectColor.deepColor),),
                                onPressed: () {
                                  SpUtil.sharedPreferences.remove('isLogin');
                                  SpUtil.sharedPreferences.remove("uid");
                                  SpUtil.sharedPreferences.remove('alias');
                                  SpUtil.sharedPreferences.remove('avatar');
                                  SpUtil.sharedPreferences.remove('desc');
                                  SpUtil.sharedPreferences.remove('isPro');
                                  SpUtil.sharedPreferences.remove('isVip');
                                  Navigator.push(context,
                                      new MaterialPageRoute(builder: (context) => new LoginWidget()));
                                },
                              ),
                            ],
                          );
                        }
                    );
                  },
                  child: Container(
                      alignment: Alignment.center,
                      child: Container(
                        width:200,
                        height: 40,
                        margin: EdgeInsets.only(bottom: 0),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color:ProjectColor.secColor,
                          borderRadius: BorderRadius.all(Radius.circular(15)),
                        ),
                        child: Text('退出登录',style: TextStyle(color: Colors.white,fontSize: 16),),
                      )
                  ),
                ),
                Spacer(),
              ],
            )
        )
    );
  }
}